<template>
  <div
    class="add-sample-dialog modal-main"
    :style="{ left: position.x + 'px', top: position.y + 'px' }"
  >
    <div
      class="dialog-header modal-header"
      @mousedown="startDrag"
      :style="{ cursor: isDragging ? 'grabbing' : 'grab' }"
    >
      <h2>{{ props.editSample ? '编辑样本' : '新增样本' }}</h2>
      <button class="close-btn" @click="$emit('close')">
        <svg
          width="20"
          height="20"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
        >
          <line x1="18" y1="6" x2="6" y2="18"></line>
          <line x1="6" y1="6" x2="18" y2="18"></line>
        </svg>
      </button>
    </div>

    <div class="dialog-content">
      <form class="sample-form">
        <div class="form-group">
          <label for="sampleName"
            >样本名称<span class="required">*</span></label
          >
          <input
            id="sampleName"
            v-model="formData.sampleName"
            type="text"
            placeholder="请输入样本名称"
            @input="validateInput"
          />
          <!-- <div v-if="sampleNameError" class="error-message">
            {{ sampleNameError }}
          </div> -->
        </div>

        <div class="form-group">
          <label for="channelNumber"
            >选择文件<span class="required">*</span></label
          >
          <select id="channelNumber" v-model="formData.fileName" placeholder="请选择文件" @input="validateInput" :disabled="!!props.editSample">
            <option
              v-for="channel in availableChannels"
              :key="channel.fileName"
              :value="channel.fileName"
            >
              {{ channel.fileName }}
            </option>
          </select>
        </div>

        <div class="form-group">
          <label for="paramName"
            >信号名称<span class="required">*</span></label
          >
          <select id="paramName" v-model="formData.paramName" placeholder="请选择信号名称" @input="validateInput" class="signal-select" :disabled="!!props.editSample">
            <option
              v-for="signal in availableSignals"
              :key="signal.name"
              :value="signal.name"
            >
              {{ signal.name }}
            </option>
          </select>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="startTime"
              >开始时间<span class="required">*</span></label
            >
            <input
              id="startTime"
              v-model="formData.startTime"
              type="number"
              step="0.001"
              :min="xMin"
              placeholder="请输入开始时间"
              @input="updateCursor"
              :disabled="!!props.editSample"
            />
            <div v-if="startTimeError" class="error-message">
              {{ startTimeError }}
            </div>
          </div>

          <div class="form-group">
            <label for="endTime">结束时间<span class="required">*</span></label>
            <input
              id="endTime"
              v-model="formData.endTime"
              type="number"
              step="0.001"
              :max="xMax"
              placeholder="请输入结束时间"
              @input="updateCursor"
              :disabled="!!props.editSample"
            />
            <div v-if="endTimeError" class="error-message">
              {{ endTimeError }}
            </div>
          </div>
        </div>

        <div class="form-group">
          <label for="minSimilarity"
            >最低相似度(%)<span class="required">*</span></label
          >
          <input
            id="minSimilarity"
            v-model="formData.similarity"
            type="number"
            min="0"
            max="100"
            step="0.01"
            placeholder="请输入最低相似度"
            @input="validateInput"
          />
        </div>

        <div class="form-actions">
          <button class="tech-btn-warn import-btn-cancel" @click="$emit('close')">
            取消
          </button>
          <button
            class="tech-btn save-btn-primary"
            :disabled="isLoading || formError"
            @click="saveSample"
          >
            {{ isLoading ? "保存中..." : "保存" }}
          </button>
        </div>
      </form>
    </div>

    <!-- Loading遮罩层 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="spinner"></div>
    </div>
  </div>

  <!-- 消息提示组件 -->
  <Message ref="messageRef" />
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from "vue";
import Message from "@/components/BaseComponents/Message.vue";
import API from './similaritySearch.api'

// 消息提示组件引用
const messageRef = ref<InstanceType<typeof Message> | null>(null);

// 当前x轴范围
const xMin = ref();
const xMax = ref();

// 错误提示
const sampleNameError = ref("");
const fileNameError = ref("");
const paramNameError = ref("");
const startTimeError = ref("");
const endTimeError = ref("");
const similarityError = ref("");

const formError = computed(() => {
  const error = sampleNameError.value ||
    fileNameError.value ||
    paramNameError.value ||
    startTimeError.value ||
    endTimeError.value ||
    similarityError.value

  if (error) {
    return true;
  } else {
    return false;
  }
});

interface SampleFormData {
  sampleName: string;
  fileName: string;
  paramName: string;
  startTime: string;
  endTime: string;
  similarity: string;
}

const props = defineProps<{
  parameters: any;
  selectedChannel: any;
  measurementData: any;
  selectedParametersInfo: any;
  editSample?: any; // 添加编辑样本的prop
}>();

const emit = defineEmits<{
  (e: "close"): void;
  (e: "save", sample: any, res: any): void;
  (e: "saveAndReopen", sample: any): void;
  (e: "updateCursors", cursors: { cursor1: number; cursor2: number }): void;
}>();

// 监听measurementData变化，自动设置时间范围
watch(
  () => props.measurementData,
  (newValue) => {
    // 在编辑模式下不自动设置时间
    if (props.editSample) {
      return;
    }
    nextTick(() => {
      // 使用currentXRange限制开始时间结束时间
      const currentXRange = newValue.currentXRange
      xMin.value = currentXRange[0].toFixed(3)
      xMax.value = currentXRange[1].toFixed(3)
      if (newValue && newValue.cursor1 !== undefined && newValue.cursor2 !== undefined) {
        // 比较大小
        if (newValue.cursor1 > newValue.cursor2) {
          formData.value.startTime = newValue.cursor2.toFixed(3);
          formData.value.endTime = newValue.cursor1.toFixed(3);
        } else {
          formData.value.startTime = newValue.cursor1.toFixed(3);
          formData.value.endTime = newValue.cursor2.toFixed(3);
        }
        validateInput();
      }
    })
  },
  { immediate: true, deep: true }
);

// 监听editSample变化，回显编辑数据
watch(
  () => props.editSample,
  (newValue) => {
    nextTick(() => {
      if (newValue) {
        // 回显编辑样本的数据
        formData.value.sampleName = newValue.sampleName || '';
        formData.value.fileName = newValue.fileName || '';
        formData.value.paramName = newValue.paramName || '';
        formData.value.startTime = newValue.startTime || '';
        formData.value.endTime = newValue.endTime || '';
        formData.value.similarity = newValue.similarity || '';
        validateInput();
      }
    })
  },
  { immediate: true, deep: true }
);

// 拖动相关状态
const position = ref({ x: 100, y: 100 });
const isDragging = ref(false);
const dragStart = ref({ x: 0, y: 0 });
const initialPosition = ref({ x: 0, y: 0 });

// 表单数据
const formData = ref<SampleFormData>({
  sampleName: "",
  fileName: "",
  paramName: "",
  startTime: "",
  endTime: "",
  similarity: "",
});

const isLoading = ref(false);

// 计算属性：可用通道
const availableChannels = computed(() => {
  //筛选出fileName有值的channelId
  const channelIds = props.selectedChannel.filter(
    (channel: any) => channel.fileName
  );
  
  // 在编辑模式下，如果记录中的文件名不在当前选项中，也要包含
  if (props.editSample && props.editSample.fileName) {
    const existingChannel = channelIds.find((ch: any) => ch.fileName === props.editSample.fileName);
    if (!existingChannel) {
      // 添加一个虚拟的通道选项
      return [
        ...channelIds,
        {
          fileName: props.editSample.fileName,
        }
      ];
    }
  }
  return channelIds;
});

// 计算属性：可用信号（连续量）
const availableSignals = computed(() => {
  if (!props.selectedParametersInfo || !Array.isArray(props.selectedParametersInfo)) {
    return [];
  }
  // 过滤出连续量参数
  const signals = props.selectedParametersInfo.filter((param: any) => param.mode == 0);
  
  // 在编辑模式下，如果记录中的信号名不在当前选项中，也要包含
  if (props.editSample && props.editSample.paramName) {
    const existingSignal = signals.find((signal: any) => signal.name === props.editSample.paramName);
    if (!existingSignal) {
      // 添加一个虚拟的信号选项
      return [
        ...signals,
        {
          name: props.editSample.paramName,
          mode: 0
        }
      ];
    }
  }
  
  return signals;
});

// 获取当前窗口实际尺寸
const getDialogSize = () => {
  const screenWidth = window.innerWidth;
  const screenHeight = window.innerHeight;

  return {
    width: Math.min(screenWidth * 0.25, 350),
    height: Math.min(screenHeight * 0.7, 600),
  };
};

// 拖动功能
const startDrag = (event: MouseEvent) => {
  if (
    event.target === event.currentTarget ||
    (event.target as Element).tagName === "H2"
  ) {
    isDragging.value = true;
    dragStart.value = { x: event.clientX, y: event.clientY };
    initialPosition.value = { x: position.value.x, y: position.value.y };
    document.addEventListener("mousemove", handleDrag);
    document.addEventListener("mouseup", stopDrag);
    event.preventDefault();
  }
};

const handleDrag = (event: MouseEvent) => {
  if (!isDragging.value) return;

  const deltaX = event.clientX - dragStart.value.x;
  const deltaY = event.clientY - dragStart.value.y;

  const dialogSize = getDialogSize();

  position.value = {
    x: Math.max(
      0,
      Math.min(
        window.innerWidth - dialogSize.width,
        initialPosition.value.x + deltaX
      )
    ),
    y: Math.max(
      0,
      Math.min(
        window.innerHeight - dialogSize.height,
        initialPosition.value.y + deltaY
      )
    ),
  };
};

const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener("mousemove", handleDrag);
  document.removeEventListener("mouseup", stopDrag);
};

// 窗口大小变化时调整位置
const handleResize = () => {
  const dialogSize = getDialogSize();
  position.value = {
    x: Math.max(
      0,
      Math.min(window.innerWidth - dialogSize.width, position.value.x)
    ),
    y: Math.max(
      0,
      Math.min(window.innerHeight - dialogSize.height, position.value.y)
    ),
  };
};

// 组件挂载时设置初始位置为居中
onMounted(() => {
  const dialogSize = getDialogSize();
  position.value = {
    x: Math.max(0, (window.innerWidth - dialogSize.width) / 2),
    y: Math.max(0, (window.innerHeight - dialogSize.height) / 2),
  };

  window.addEventListener("resize", handleResize);
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener("mousemove", handleDrag);
  document.removeEventListener("mouseup", stopDrag);
  window.removeEventListener("resize", handleResize);
  
  // 清理防抖计时器
  if (updateCursorTimeout) {
    clearTimeout(updateCursorTimeout);
  }
});

//输入时进行验证
const validateInput = () => {
  //验证样本名称
  if (!formData.value.sampleName) {
    sampleNameError.value = "请输入样本名称";
  } else {
    sampleNameError.value = "";
  }
  //验证通道号
  if (!formData.value.fileName) {
    fileNameError.value = "请选择文件";
  } else {
    fileNameError.value = "";
  }
  //验证信号名称
  if (!formData.value.paramName) {
    paramNameError.value = "请选择信号名称";
  } else {
    paramNameError.value = "";
  }
  //验证开始时间 需要大于等于0
  if (formData.value.startTime === '' || formData.value.startTime === null || formData.value.startTime === undefined) {
    startTimeError.value = "请输入开始时间";
  } else if (parseFloat(formData.value.startTime) < 0) {
    startTimeError.value = "开始时间必须大于等于0";
  } else {
    startTimeError.value = "";
  }
  if (parseFloat(formData.value.startTime) < xMin.value) {
    formData.value.startTime = xMin.value.toFixed(3);
    startTimeError.value = "开始时间必须大于等于0";
  }

  //验证结束时间
  if (formData.value.endTime === '' || formData.value.endTime === null || formData.value.endTime === undefined) {
    endTimeError.value = "请输入结束时间";
  } else {
    endTimeError.value = "";
  }
  if (parseFloat(formData.value.endTime) > xMax.value) {
    formData.value.endTime = xMax.value.toFixed(3);
    endTimeError.value = "结束时间必须小于等于最大时间";
  }
  //验证开始时间不能大于结束时间
  if (parseFloat(formData.value.startTime) >= parseFloat(formData.value.endTime)) {
    // 如果光标在开始时间，那么清空开始时间的输入，如果在结束时间，则清空结束时间的输入
    const activeElement = document.activeElement;
    if (activeElement && activeElement.id === 'startTime') {
      // 如果光标在开始时间输入框，清空开始时间
      // formData.value.startTime = '';
      startTimeError.value = "开始时间不能大于等于结束时间";
    } else if (activeElement && activeElement.id === 'endTime') {
      // 如果光标在结束时间输入框，清空结束时间
      // formData.value.endTime = xMax;
      endTimeError.value = "结束时间不能小于等于开始时间";
    } else {
      // 如果光标不在任何输入框上，设置错误信息
      startTimeError.value = "开始时间不能大于等于结束时间";
      endTimeError.value = "结束时间不能小于等于开始时间";
    }
  }
  //验证最低相似度
  if (formData.value.similarity === '' || formData.value.similarity === null || formData.value.similarity === undefined) {
    similarityError.value = "请输入最低相似度";
  } else {
    similarityError.value = "";
  }
};

// 添加防抖计时器
let updateCursorTimeout: number | null = null;

const updateCursor = (event: Event) => {
  validateInput();
  
  // 在编辑模式下不触发游标更新
  if (props.editSample) {
    return;
  }
  
  // 清除之前的计时器
  if (updateCursorTimeout) {
    clearTimeout(updateCursorTimeout);
  }
  
  // 设置防抖延迟，避免频繁触发
  updateCursorTimeout = setTimeout(() => {
    // 获取输入的时间
    const startTime = parseFloat(formData.value.startTime);
    const endTime = parseFloat(formData.value.endTime);
    
    // 验证时间有效性
    if (!isNaN(startTime) && !isNaN(endTime)) {
      // 发送游标更新事件到父组件
      emit("updateCursors", {
        cursor1: startTime,
        cursor2: endTime
      });
    }
  }, 1500); // 1500ms延迟
};

// 保存样本
const saveSample = async () => {
  const startTime = parseFloat(formData.value.startTime);
  const endTime = parseFloat(formData.value.endTime);

  if (startTime >= endTime) {
    messageRef.value?.show({
      type: "warning",
      content: "结束时间必须大于开始时间",
      duration: 3000,
    });
    return;
  }

  // 验证相似度
  const similarity = parseFloat(formData.value.similarity);
  if (similarity < 0 || similarity > 100) {
    messageRef.value?.show({
      type: "warning",
      content: "最低相似度必须在0-100之间",
      duration: 3000,
    });
    return;
  }

  isLoading.value = true;

  try {
    // 模拟API调用
    let newSample = {};
    let res = {};
    if (props.editSample) {
      // 编辑
      newSample = {
        id: props.editSample.id,
        sampleName: formData.value.sampleName,
        similarity: parseFloat(formData.value.similarity),
      };
      res = await API.updateSample(newSample)
    } else {
      // 新增
      newSample = {
        sampleName: formData.value.sampleName,
        fileName: formData.value.fileName,
        paramName: formData.value.paramName,
        startTime: formData.value.startTime,
        endTime: formData.value.endTime,
        similarity: parseFloat(formData.value.similarity),
      };
      res = await API.addSample(newSample)
    }
    emit("save", newSample, res);
  } catch (error: any) {
    messageRef.value?.show({
      type: "warning",
      content: error.response.data.msg,
      duration: 3000,
    });
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
@import '../../../src/assets/css/theme.css';
@import '../../../src/assets/css/buttons.css';
@import '../../../src/assets/css/modal.css';
* {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.import-btn-cancel, .save-btn-primary {
    height: 36px;
    font-size: 0.875rem;
    padding: 0.35rem 0.75rem;
    border-radius: 0.375rem;
    cursor: pointer;
    transition: all 0.2s ease;
}
.add-sample-dialog {
  position: fixed;
  width: auto;
  min-height: fit-content;
  max-height: 80vh;
  backdrop-filter: blur(10px);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  border: 1px solid rgba(30, 64, 175, 0.2);
  z-index: 9999;
  animation: modalAppear 0.3s ease-out;
}

@keyframes modalAppear {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.add-sample-dialog::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  //background: linear-gradient(
  //  90deg,
  //  rgba(56, 189, 248, 0.5) 0%,
  //  rgba(30, 64, 175, 0.8) 50%,
  //  rgba(56, 189, 248, 0.5) 100%
  //);
  z-index: 3;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  position: relative;
  z-index: 2;
  user-select: none;
  transition: background-color 0.2s ease;
}

.dialog-header h2 {
  margin: 0;
  color: var(--text-color);
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  color: var(--text-color);
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: rgba(0, 0, 0, 0.85);
}

.dialog-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.sample-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group label {
  font-weight: 600;
  color: var(--text-color);
  font-size: 14px;
}

.form-group input,
.form-group select {
  padding: 10px 12px;
  border-radius: 6px;
  background: var(--select-background);
  color: var(--text-color);
  border: 1px solid var(--input-border-color);
  font-size: 14px;
  transition: all 0.2s ease;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-group input:disabled,
.form-group select:disabled {
  background: var(--disabled-color);
  color: var(--text-color);
  cursor: not-allowed;
}

.form-group input::placeholder {
  color: var(--preview-text-color);
}

.signal-select {
  max-height: 120px;
  overflow-y: auto;
}

.signal-select::-webkit-scrollbar {
  width: 8px;
}

.signal-select::-webkit-scrollbar-track {
  background: var(--webkit-track-color);
  border-radius: 4px;
}

.signal-select::-webkit-scrollbar-thumb {
  background: var(--webkit-thumb-color);
  border-radius: 4px;
}

.signal-select::-webkit-scrollbar-thumb:hover {
  background: var(--webkit-thumb-hover-color);
}

.signal-select option {
  padding: 8px 12px;
  font-size: 13px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--modal-divide);
}

.required {
  color: var(--error-color);
}

.error-message {
  color: var(--error-color);
  font-size: 12px;
  margin-top: 4px;
}

/* Loading样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: var(--loading-bg-color);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  border-radius: 12px;
}

.spinner {
  border: 5px solid #fcfcfc;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .add-sample-dialog {
    width: 85vw;
    min-height: fit-content;
    max-height: 85vh;
    max-width: 350px;
    max-height: 600px;
  }

  .dialog-header {
    padding: 12px 16px;
  }

  .dialog-header h2 {
    font-size: 16px;
  }

  .dialog-content {
    padding: 16px;
  }

  .form-row {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .form-group input,
  .form-group select {
    padding: 8px 10px;
    font-size: 13px;
  }

}
</style>
